package org.dtrd.modules.patient.controller;


import cn.hutool.core.util.StrUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.dtrd.base.BaseController;
import org.dtrd.common.api.vo.Result;
import org.dtrd.modules.base.service.BaseCommonService;
import org.dtrd.modules.patient.entity.bean.group.GroupDetail;
import org.dtrd.modules.patient.entity.bean.group.GroupListInfo;
import org.dtrd.modules.patient.service.IDtrdEntRdGroupService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

import static org.dtrd.common.constant.CommonConstant.*;
import static org.dtrd.config.system.SystemState.ResponseState.*;

/**
 * <p>
 * 患者分组 前端控制器
 * </p>
 * @author QR
 * @since 2022-03-03
 */
@Api(tags = "患者分组")
@RestController
@RequestMapping("/group/")
public class GroupController extends BaseController {

    @Autowired
    private IDtrdEntRdGroupService groupService;
    @Autowired
    private BaseCommonService baseCommonService;

    @ApiOperation(value = "查询患者分组详情", response = GroupDetail.class)
    @GetMapping("get")
    public Result<?> getGroup(@RequestParam Integer id){
        GroupDetail info = groupService.getGroup(id);
        String logContent = String.format("查询患者分组详情，查询id：%d", id);
        baseCommonService.addLog(logContent, OPERATE_TYPE_QUERY);
        return Result.OK(info);
    }

    @ApiOperation(value = "查询患者分组列表", response = GroupListInfo.class)
    @GetMapping("list")
    public Result<?> getGroupList(){
        List<GroupListInfo> list = groupService.getGroupList();
        String logContent = "查询患者分组列表";
        baseCommonService.addLog(logContent, OPERATE_TYPE_QUERY);
        return Result.OK(list);
    }

    @ApiOperation("新增或修改患者分组")
    @PostMapping("saveorupdate")
    public Result<?> saveOrUpdateGroup(@RequestBody GroupDetail dto){
        if (StrUtil.isBlank(dto.getGroupName())) {
            return error(STATE_PARAMS_ERROR);
        }
        if (!groupService.isValidGroupName(dto.getGroupName(), dto.getDataId(), dto.getOrgCode())) {
            return Result.error("分组名重复");
        }
        boolean result = groupService.saveOrUpdateGroup(dto);
        String logContent = String.format("新增或修改患者分组, 修改内容%s", dto);
        baseCommonService.addLog(logContent, OPERATE_TYPE_SAVE_OR_UPDATE);
        return result ? Result.OK() : error(STATE_OPERATION_FAILURE);
    }

    @ApiOperation("删除患者分组")
    @DeleteMapping("remove")
    public Result<?> removeGroup(@RequestParam Integer id){
        if(isIntParamInvalid(id)) {
            return error(STATE_PARAMS_MISSING);
        }
        boolean result = groupService.removeGroup(id);
        String logContent = String.format("删除患者分组, 删除id: %d", id);
        baseCommonService.addLog(logContent, OPERATE_TYPE_DELETE);
        return result ? Result.OK() : error(STATE_OPERATION_FAILURE);
    }
}
